<?php

use Core\ResourceController;
use Models\Product;
use Models\Item;
use Models\Evaluate;

class GoodsController extends ResourceController
{
    public function index()
    {
        $product = new Product;

        if ($this->input->get('keyword')) {
            $product->like('title', $this->input->get('keyword'));
        }

        if (in_array($this->input->get('order'), ['solded desc', 'price', 'price desc', 'id desc'])) {
            $product->order_by($this->input->get('order'));
        }

        if ($this->input->get('category_id')) {
            $category_id = $this->input->get('category_id');
            $product->group_start()
                ->or_where([
                    'category_id' => $category_id,
                    'category_id2' => $category_id
                ])
                ->group_end();
        }
        $pages = $product->select('id,thumbnail,title,en_title,price,solded,unit')->where('status', 1)->order_by('sort desc')->paginate(20)->to_array();

        return $this->response($pages);
    }

    public function detail($id)
    {
        $product = (new Product)->find($id);
        if (!$product) {
            return $this->notFoundResponse();
        }

        $specs = (new Item)
            ->where('product_id', $product['id'])
            ->get();


        $evaluates = (new Evaluate)
            ->where([
                'product_id' => $product['id'],
                'status' => 1
            ])
            ->order_by('id desc')
            ->with('user')
            ->limit(20)
            ->get();

        $favorite = $product->is_favorite($this->session->authUser['id']);

        // 相关推荐
        if ($product['recommends']) {
            $recommends = Product::where("id in({$product['recommends']})")->limit(4)->get();
        } else {
            $recommends = Product::where('category_id', $product['category_id'])
                            ->order_by('is_recommend desc,sort desc')
                            ->limit(4)
                            ->get();
        }

        return $this->response([
            'goods' => $product,
            'specs' => $specs,
            'evaluates' => $evaluates,
            'favorite' => $favorite,
            'recommends' => $recommends
        ]);
    }
}
